import React, { Component } from 'react'

import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage } from '../../../components/TableCustomize'
import { Button, Drawer, Alert, Badge, Divider, Menu, Modal, Select } from 'antd'
import { Link } from 'react-router-dom'
import TopInquire from './TopInquire'
import img from '../../../assets/img/flame.png'
import * as StockRequisition from '../../../axios/StockRequisition'
import * as StayGrantService from '../../../axios/StayGrant'
import { withPermission } from '../../../components/withpermission'
const RefreshButton = withPermission(Button, 'sync')
const CHFButton = withPermission(Button, 'cuihuifu')
const BJButton = withPermission(Button, 'bianjijiaoqi')
const TJButton = withPermission(Button, 'tijiaoqianliao')
const PrintButton = withPermission(Button, 'printer')
export default class Inquire extends Component {
    state = {
        columns: [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                render: (text, record, index) =>
                    <div style={{ display: 'flex' }}>
                        <div>{index + 1}</div>
                        {record.anxious ? <img src={img} style={{ width: '18px', height: '18px' }} /> : null}
                    </div>,
                width: 60,
            },
            {
                title: '领料单号',
                dataIndex: 'acceptCode',
                sorter: (a, b) => compareNum(a.acceptCode, b.acceptCode),
                width: 150,
            },
            {
                title: '批号',
                dataIndex: 'batchNo',
                key: 'batchNo',
                sorter: (a, b) => compareNum(a.batchNo, b.batchNo),
                width: 100,
            },
            {
                title: '机型',
                dataIndex: 'model',
                key: 'model',
                sorter: (a, b) => compareNum(a.model, b.model),
                width: 180,
            },
            {
                title: '装配部门',
                dataIndex: 'departName',
                sorter: (a, b) => compareNum(a.departName, b.departName),
                width: 120,
            },
            {
                title: '领料班组',
                dataIndex: 'groupName',
                sorter: (a, b) => compareNum(a.groupName, b.groupName),
                width: 100,
            },
            {
                title: '班组长',
                dataIndex: 'groupLeader',
                sorter: (a, b) => compareNum(a.groupLeader, b.groupLeader),
                width: 80,
            },
            {
                title: '领料项',
                dataIndex: 'acceptItem',
                sorter: (a, b) => compareNum(a.acceptItem, b.acceptItem),
                width: 80,
            },
            {
                title: '申请时间',
                dataIndex: 'createTime',
                sorter: (a, b) => compareNum(a.createTime, b.createTime),
                width: 150,
            },
            {
                title: '第一交机时间',
                dataIndex: 'firstDeliveryTime',
                sorter: (a, b) => compareNum(a.firstDeliveryTime, b.firstDeliveryTime),
                width: 150,
            },
            {
                title: '操作',
                dataIndex: 'opes',
                width: 100,
                render: (text, record, index) =>
                    <Link onClick={this.detail.bind(null, record)} to='/getParticulars'>{'批量明细'}</Link>
            },
            { dataIndex: '' }
        ],
        dataSource: [
        ],
        columnsInterior: [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                render: (text, record, index) =>
                    <div style={{ display: 'flex' }}>
                        <div>{index + 1}</div>
                        {record.isRush === 1 ? <img src={img} style={{ width: '18px', height: '18px' }} /> : null}
                    </div>,
                width: 60,
            },
            {
                title: '物料编码',
                dataIndex: 'partCode',
                sorter: (a, b) => compareNum(a.partCode, b.partCode),
                width: 100,
            },
            {
                title: '图号',
                dataIndex: 'paperCode',
                sorter: (a, b) => compareNum(a.paperCode, b.paperCode),
                width: 180,
            },
            {
                title: '部件',
                dataIndex: 'component',
                width: 100,
            },
            {
                title: '物料名称',
                dataIndex: 'partName',
                width: 100,
            },
            {
                title: '物料规格',
                dataIndex: 'partSpec',
                sorter: (a, b) => compareNum(a.partSpec, b.partSpec),
                width: 100,
            },
            {
                title: '领料数量',
                dataIndex: 'acceptNum',
                sorter: (a, b) => compareNum(a.acceptNum, b.acceptNum),
                width: 100,
            },
            {
                title: '发料状态',
                dataIndex: 'outStatus',
                sorter: (a, b) => compareNum(a.outStatus, b.outStatus),
                width: 100,
                render: (text, record, index) =>
                    <div>
                        {/* <div>
                            {
                                record.owe ? <Badge status="error" text={<span style={{ color: 'red' }}>欠料</span>} /> : null
                            }
                        </div> */}
                        <div>
                            {
                                text === 1 ? <Badge status="processing" text='待确认' /> : text === 2 ? <Badge status="success" text="未完成" /> : text === 3 ? <Badge status="success" text="已完成" /> : null
                            }
                        </div>
                    </div>
            },
            {
                title: '发料仓库',
                dataIndex: 'storeName',
                width: 100,
            },
            {
                title: '领料单批次',
                dataIndex: 'batchNum',
                width: 120,
                sorter: (a, b) => compareNum(a.batchNum, b.batchNum),
            },
            { dataIndex: '' }
        ],
        dataSourceInterior: [
        ],
        advanced: false,
        selectedRows: [],
        paging: {},
        loginFlag: false,
        values: {},
        selectedRowKeys: [],
        selectedRows: [],
        selectedRowKeys1: [],
        selectedRows1: [],
        some: null,
        row: [],
        row1: [],
    }
    // 挂载前
    UNSAFE_componentWillMount() {
        this.fetch()
        this.getWorkShopList()
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (page = 1, size = 100) => {
        const { values } = this.state
        this.setState({
            loading: true,
            one: false,
            drawerVisible: false,
            formData: {},
            values: {},
            // 操作后清除选中
            selectedRowKeys: [],
            selectedRows: [],
            selectedRowKeys1: [],
            selectedRows1: [],
            some: null,
            paging: { pageNum: page, pageSize: size }
        })
        let a = { pageNum: page, pageSize: size }
        setTimeout(() => {
            this.search({ ...values, ...a })
        }, 300);
    }
    // 查询接口
    search = (value, paging) => {
        let userId = localStorage.getItem('userId')
        StockRequisition.acceptCodeQuery({ ...value, ...paging, userId: userId }).then((item) => {
            console.log('查询数据', item);
            if (item.data.code === 200) {
                this.setState({
                    loading: false,
                    dataSource: item.data.data,
                    // 操作后清除选中
                    selectedRowKeys: [],
                    selectedRows: [],
                    some: null,
                    paging: {
                        pageNum: item.data.pageNum,
                        pageSize: item.data.pageSize,
                        total: item.data.total,
                    }
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    getWorkShopList = () => {
        StayGrantService.workShopList().then(res => {
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            const workShopList = res.data && res.data.data ? res.data.data : []
            this.setState({ workShopList })
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    onExpand = (expanded, record) => {
        // const { row } = this.state
        // let id = row.length > 0 ? row[0] : null
        // if (id == record.id) {
        //     expanded = false
        // }
        if (expanded) {
            let userId = localStorage.getItem('userId')
            StockRequisition.acceptCodeQueryDetail({ id: record.id, userId: userId, pageSize: 99999 }).then(res => {
                console.log('展开', res);
                this.setState({
                    dataSourceInterior: res && res.data ? res.data.data : [],
                    row: [record.id],
                })
            })
            return
        }
        this.setState({
            row: [],
        })

    }
    // 高级查询
    advancedss = () => {
        console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    // 刷新
    refresh = () => {
        console.log('刷新');
        this.fetch();
    }
    // 查询
    handleSearch = value => {
        console.log('查询', value)
        const { paging } = this.state
        this.search(value, paging)
        this.setState({ searchItem: value });
    };
    // 重置
    cz = () => {
        this.setState({
            values: null
        }, () => { this.fetch() })

    }
    // 批量明细
    detail = (record) => {
        console.log('批量明细', record);
        localStorage.setItem('detailData', JSON.stringify(record.acceptCode))
    }
    render() {
        const { workShopList, selectedRowKeys, paging, columns, loading, dataSource, advanced, selectedRowKeys1 } = this.state
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                let some = [...selectedRows].length
                this.setState({
                    some: some,
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows
                })
            },
        }
        const expandedRowRender = () => {
            const { columnsInterior, dataSourceInterior } = this.state
            const rowSelection = {
                type: 'checkbox',
                selectedRowKeys: selectedRowKeys1,
                onChange: (selectedRowKeys1, selectedRows1) => {
                    console.log(`内部table-selectedRowKeys: ${selectedRowKeys1}`, 'selectedRows: ', selectedRows1);
                    this.setState({
                        selectedRowKeys1: selectedRowKeys1,
                        selectedRows1: selectedRows1
                    })
                },
            }
            return <TableCustomize
                rowSelection={rowSelection}
                columns={columnsInterior}
                rowKey={(record) => record.id}
                dataSource={dataSourceInterior}
                pagination={false}
                expandedRowKeys={this.state.row1}
                allowDrafting={true}
                scroll={{ y: 300 }}
                rowClassName={(record, index) => {
                    return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                }}
            />;
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <TopInquire onSearch={this.handleSearch}
                        onClick4={this.advancedss}
                        advanced={advanced}
                        onClick={this.cz}
                        workShopList={workShopList}
                    ></TopInquire>
                </BasicLayoutSearch>
                <BasicLayout
                    name='领料单查询'
                    icon="table"
                    buttons={[
                        <RefreshButton key={1} onClick={() => this.refresh()} icon='sync' />,
                        // <PrintButton key={2} onClick={() => this.print()} />,
                        // <TJButton key={3} onClick={() => this.putIn()} />,
                        // <BJButton key={4} onClick={() => this.redact()} />,
                        // <CHFButton key={5} onClick={() => this.urge()} />,

                        // <Button key={1} onClick={this.refresh} type='primary'>刷新</Button>
                    ]}
                >
                    <TableCustomize
                        rowSelection={rowSelection}
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        expandRowByClick={true}
                        expandedRowKeys={this.state.row}
                        rowClassName={(record, index) => {
                            return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                        }}
                        // onRow={(record, index) => ({
                        //     onClick: this.onExpand.bind(this, true, record)
                        // })}
                        onExpand={(expanded, record) => this.onExpand(expanded, record)}
                        expandedRowRender={expandedRowRender}
                        scroll={{ y: 600 }}
                    >
                    </TableCustomize>
                    <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
                </BasicLayout>
            </div>
        )
    }
}
